<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="60%">
    <!-- 表单 -->
    <el-form ref="ruleForm" :model="dataForm" :rules="dataRules" label-width="130px">
      <el-row>
        <el-col :span="10">
          <el-form-item label="公司名称" prop="companyName">
            <el-input v-if="disabledActive" v-model="companyNameVal" :disabled="disabledActive"></el-input>
            <el-autocomplete
              style="width:100%"
              clearable
              v-else
              @clear="handleClear"
              v-model="dataForm.companyName"
              :fetch-suggestions="querySearch"
              placeholder="请输入公司名称"
              :trigger-on-focus="false"
              @select="handleSelect"
            ></el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="公司类型">
            <el-input v-model="companyTypeName" readonly disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="单位地址">
            <el-input v-model="companyAddress" readonly disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="用水量" prop="totalWater">
            <el-input type="number" v-model.trim="dataForm.totalWater" @input="handleWater"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 用水详细 -->
      <el-row>
        <el-col :span="6" v-for="(item,itemIndex) in listData" :key="item.name">
          <el-form-item :label="item.name">
            <el-input type="number" v-model.trim="item.value" @input="handleQuarter(itemIndex)"></el-input>
          </el-form-item>
          <el-form-item :label="list.monthName" v-for="list in item.item" :key="list.monthName">
            <el-input type="number" v-model.trim="list.monthValue" @input="handleMonth(itemIndex)"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="用水类型" prop="waterTypeId">
            <el-select v-model="dataForm.waterTypeId" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in waterTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="申报日期">
            <el-date-picker
              v-model="dataForm.applyDate"
              type="date"
              placeholder="选择日期"
              style="width:100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="所属周期" prop="cycleDate">
            <el-date-picker
              v-model="dataForm.cycleDate"
              type="year"
              value-format="yyyy"
              placeholder="选择年"
              style="width:100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="是否超计划申报">
            <el-radio v-model="dataForm.planStatus" label="1">是</el-radio>
            <el-radio v-model="dataForm.planStatus" label="0">否</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer" v-if="type !=='info'">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getAllCompany, getAllWaterType } from '@/api/base'
import {
  insertWaterDeclare,
  updateWater,
  catWaterDeclareById,
  getCompanyInfoByUserId,
} from '@/api/other'
import { listDataVal } from '@/config/dataList'
import { confirm } from '@/config/publicMethod'
export default {
  data() {
    return {
      dialogVisible: false,
      title: '',
      type: '',
      dataForm: {
        companyId: '',
        companyName: '',
        cycleDate: this.ShowYear(0),
        planStatus: '0',
        waterTypeId: '',
        applyDate: this.ShowDate(0),
        totalWater: 0, // 用水量
        insertWaterDeclareItemRequests: [],
        updateWaterDeclareItemRequests: [],
        id: '',
      },
      dataRules: {
        companyName: [
          { required: true, message: '请输入公司', trigger: 'change' },
        ],
        totalWater: [
          { required: true, message: '请输入用水量', trigger: 'blur' },
        ],
        waterTypeId: [
          { required: true, message: '请选择公司', trigger: 'change' },
        ],
        cycleDate: [
          { required: true, message: '请选择公司', trigger: 'change' },
        ],
      },
      listData: listDataVal(),
      companyList: [],
      waterTypeList: [], // 用水类型
      companyAddress: '', // 公司地址
      companyTypeName: '', // 公司类型
      disabledActive: false,
      companyNameVal: '', // 公司所下的角色上报用
    }
  },
  mounted() {},
  methods: {
    async init(type, item) {
      this.dialogVisible = true
      this.title = type == 'new' ? '新增' : type == 'edit' ? '编辑' : '详情'
      this.type = type
      this.dataForm.id = item ? item.id : undefined
      if (type == 'new') {
        // 获取vuex中公司信息
        const { userObj } = this.$store.state && this.$store.state.user
        const { id } = userObj.roles[0] // 角色权限id
        const userId = userObj.id // 角色账号id
        if (id == '1' || id == '2') {
          //管理账号 普通账号
          this.dataRules.companyName[0].required = true
          this.disabledActive = false
          this.dataForm.companyId = ''
          this.dataForm.companyName = ''
          this.companyTypeName = ''
          this.companyAddress = ''
        } else {
          // 其他账号 (公司的角色id)
          let res = await this.getCompanyInfoByUserIdFun(userId)
          this.disabledActive = true
          this.dataForm.companyId = res.id
          this.companyNameVal = res.companyName
          this.companyTypeName = res.companyTypeResponse.companyTypeName
          this.companyAddress = res.companyAddress
          this.dataRules.companyName[0].required = false
        }
        this.dataForm.totalWater = ''
        this.dataForm.cycleDate = this.ShowYear(0)
        this.dataForm.waterTypeId = ''
        this.dataForm.planStatus = '0'
        this.listData.forEach((el) => {
          el.value = 0
          el.item.forEach((ele) => {
            ele.monthValue = 0
          })
        })
        this.$nextTick((_) => {
          this.$refs['ruleForm'].resetFields()
        })
      } else {
        // 详情
        this.catWaterDeclareByIdReq(item.id)
      }
      this.getAllCompanyReq() // 所有公司
      this.getAllWaterTypeReq() // 用水类型
    },
    getAllCompanyReq() {
      getAllCompany({ page: 1, pageSize: 100 }).then((res) => {
        const { code, data, msg } = res
        if (code !== '0000') return this.$message.error(msg)
        this.companyList = data.list
      })
    },
    getAllWaterTypeReq() {
      getAllWaterType().then((res) => {
        const { code, data, msg } = res
        if (code !== '0000') return this.$message.error(msg)
        this.waterTypeList = data
      })
    },
    // 根据角色id获取公司信息
    async getCompanyInfoByUserIdFun(userId) {
      let result = {}
      const { code, data, msg } = await getCompanyInfoByUserId({ userId })
      if (code !== '0000') return this.$message.error(msg)
      result = { ...data }
      return result
    },
    catWaterDeclareByIdReq(id) {
      catWaterDeclareById({ id }).then((res) => {
        const { code, data, msg } = res
        if (code !== '0000') return this.$message.error(msg)
        this.disabledActive = true
        this.dataRules.companyName[0].required = false

        this.dataForm.companyId = data.companyId + '' //'1' // 公司id
        this.companyNameVal = data.companyName // 公司名称
        this.companyAddress = data.companyAddress // 公司地址

        this.companyTypeName = data.companyTypeResponse.companyTypeName
        this.dataForm.totalWater = data.totalWater
        this.dataForm.cycleDate = data.cycleDate + ''
        this.dataForm.applyDate = data.applyDate
        this.dataForm.planStatus = data.planStatus + ''
        this.dataForm.waterTypeId =
          data.waterTypeResponse && data.waterTypeResponse.id
        // 季度
        this.listData[0].value = data.firstQuarter
        this.listData[1].value = data.secondQuarter
        this.listData[2].value = data.thirdQuarter
        this.listData[3].value = data.fourthQuarter
        let result = data.insertWaterDeclareItemResponses
        // 月份遍历的方法
        this.listData[0].item[0].monthValue = result[0].water // 一月份
        this.listData[0].item[1].monthValue = result[1].water // 二月份
        this.listData[0].item[2].monthValue = result[2].water // 三月份
        this.listData[1].item[0].monthValue = result[3].water // 四月份
        this.listData[1].item[1].monthValue = result[4].water // 五月份
        this.listData[1].item[2].monthValue = result[5].water // 六月份
        this.listData[2].item[0].monthValue = result[6].water // 七月份
        this.listData[2].item[1].monthValue = result[7].water // 八月份
        this.listData[2].item[2].monthValue = result[8].water // 九月份
        this.listData[3].item[0].monthValue = result[9].water // 十月份
        this.listData[3].item[1].monthValue = result[10].water // 十一月份
        this.listData[3].item[2].monthValue = result[11].water // 十二月份
        // this.listData.forEach((el, elIndex) => {
        //   el.item.forEach((ele, eleIndex) => {
        //     data.insertWaterDeclareItemResponses.forEach((list, listIndex) => {
        //       el.item[eleIndex].monthValue = Number(list.water)
        //     })
        //   })
        // })
      })
    },
    handleSelect(item) {
      this.dataForm.companyId = item.id
      this.companyTypeName = item.companyTypeResponse.companyTypeName
      this.companyAddress = item.companyAddress
    },
    handleChange(event) {
      let obj
      this.companyList.forEach((el) => {
        if (el.id === event) obj = el
      })
      let { companyAddress, companyTypeResponse } = obj
      this.companyAddress = companyAddress // 公司地址
      this.companyTypeName = companyTypeResponse.companyTypeName // 公司类型
    },
    // 清空的回调
    handleClear() {
      this.companyAddress = ''
      this.companyTypeName = ''
      this.dataForm.companyId = ''
      this.dataForm.companyName = ''
      this.companyNameVal = ''
    },
    handleSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return
        if (this.type == 'new') {
          this.dataForm.insertWaterDeclareItemRequests = this.monthFun()
          delete this.dataForm.updateWaterDeclareItemRequests
          delete this.dataForm.id
        } else {
          this.dataForm.updateWaterDeclareItemRequests = this.monthFun()
          delete this.dataForm.insertWaterDeclareItemRequests
        }
        delete this.dataForm.totalWater
        delete this.dataForm.companyName
        if(!this.dataForm.companyId) return this.$message.info('公司名称不能为空,联系管理员添加公司信息')
        const res = await confirm('确定提交该数据,五个工作日后无法做修改,删除')
        if (res) {
          const api =
            this.type == 'new'
              ? insertWaterDeclare(this.dataForm)
              : updateWater(this.dataForm)
          api.then((res) => {
            const { code, msg } = res
            if (code !== '0000') return this.$message.error(msg)
            this.dialogVisible = false
            this.$emit('updata')
          })
        }
      })
    },
    // 获取每个月的用水数据
    monthFun() {
      let monthList = []
      this.listData.forEach((ele) => {
        ele.item.forEach((el) => {
          let obj = {
            month: 0,
            water: 0,
          }
          obj.month = el.monthId
          obj.water = el.monthValue
          monthList.push(obj)
        })
      })
      return monthList
    },
    //用水量分配
    handleWater() {
      const quarterWater = this.dataForm.totalWater / 4
      this.listData.forEach((ele) => {
        ele.value = quarterWater // 季度水
        ele.item.forEach((el) => {
          el.monthValue = (ele.value / 3).toFixed(2) // 月份水
        })
      })
    },
    // 季度计算
    handleQuarter(itemIndex) {
      const { value, item } = this.listData[itemIndex]
      const num = (value / 3).toFixed(2)
      item.forEach((el) => {
        el.monthValue = num
      })
      this.waterNumberFun()
    },
    // 月份计算
    handleMonth(itemIndex) {
      const { item } = this.listData[itemIndex]
      let val = 0
      item.forEach((el) => {
        val += Number(el.monthValue)
      })
      this.listData[itemIndex].value = val
      this.waterNumberFun()
    },
    // 用水量总和
    waterNumberFun() {
      let number = 0
      this.listData.forEach((el) => {
        number += Number(el.value)
      })
      this.dataForm.totalWater = number
    },
  },
}
</script>

<style>
</style>
